package com.micro.service.auth.server.utils;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author lvxiucai
 * @description 线程池，异步任务处理
 * @date 2019/9/29
 */
@Configuration
@EnableAsync
public class AsyncThreadPool implements AsyncConfigurer{

    private static final int corePoolSize = 20;
    private static final int maxPoolSize = 100;
    private static final int keepAliveSeconds = 60;
    private static final int queueCapacity = 1000;
    private static final String prefixThreadName = "jianghu-auth-pool-";

    @Bean
    public Executor getExecutor(){
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setCorePoolSize(corePoolSize);
        threadPoolTaskExecutor.setMaxPoolSize(maxPoolSize);
        threadPoolTaskExecutor.setKeepAliveSeconds(keepAliveSeconds);
        threadPoolTaskExecutor.setQueueCapacity(queueCapacity);
        threadPoolTaskExecutor.setThreadNamePrefix(prefixThreadName);

        //当线程池达到最大max_size时，如何处理新任务，即在当前调用所在的线程处理
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        threadPoolTaskExecutor.setWaitForTasksToCompleteOnShutdown(true);
        threadPoolTaskExecutor.setAwaitTerminationSeconds(60);
        threadPoolTaskExecutor.initialize();

        return threadPoolTaskExecutor;
    }

    public static void main(String[] args) {
        AsyncThreadPool pool = new AsyncThreadPool();
        for (int i = 0; i < 100; i++) {
            pool.getExecutor().execute(()->{
                System.out.println("当前线程"+Thread.currentThread().getName());
            });
        }

    }

}
